<!DOCTYPE html>
<html lang="zh-CN">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="robots" content="noodp" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
        <title>《Flutter界面跳转数据交互界面混合开发》 - Lucklyの博客 - 在阅读中遇见自己</title><meta name="Description" content="早起的年轻人做的网站"><meta property="og:title" content="《Flutter界面跳转数据交互界面混合开发》" />
<meta property="og:description" content="
本文主要介绍
" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://luckly.work/flutter%E7%95%8C%E9%9D%A2%E8%B7%B3%E8%BD%AC%E6%95%B0%E6%8D%AE%E4%BA%A4%E4%BA%92%E7%95%8C%E9%9D%A2%E6%B7%B7%E5%90%88%E5%BC%80%E5%8F%91/" />
<meta property="og:image" content="https://luckly.work/logo.png"/>
<meta property="article:published_time" content="2021-07-31T21:50:37+08:00" />
<meta property="article:modified_time" content="2021-07-31T21:50:37+08:00" />
<meta name="twitter:card" content="summary_large_image"/>
<meta name="twitter:image" content="https://luckly.work/logo.png"/>

<meta name="twitter:title" content="《Flutter界面跳转数据交互界面混合开发》"/>
<meta name="twitter:description" content="
本文主要介绍
"/>
<meta name="application-name" content="LoveIt">
<meta name="apple-mobile-web-app-title" content="LoveIt"><meta name="theme-color" content="#ffffff"><meta name="msapplication-TileColor" content="#da532c"><link rel="shortcut icon" type="image/x-icon" href="/favicon.ico" />
        <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
        <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png"><link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png"><link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5"><link rel="manifest" href="/site.webmanifest"><link rel="canonical" href="https://luckly.work/flutter%E7%95%8C%E9%9D%A2%E8%B7%B3%E8%BD%AC%E6%95%B0%E6%8D%AE%E4%BA%A4%E4%BA%92%E7%95%8C%E9%9D%A2%E6%B7%B7%E5%90%88%E5%BC%80%E5%8F%91/" /><link rel="prev" href="https://luckly.work/flutter%E6%B8%B2%E6%9F%93%E5%8E%9F%E7%90%86%E4%B8%8E%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96/" /><link rel="next" href="https://luckly.work/flutter%E5%AD%A6%E4%B9%A0%E8%B5%84%E6%96%99%E6%95%B4%E7%90%863/" /><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/normalize.css@8.0.1/normalize.min.css"><link rel="stylesheet" href="/css/style.min.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.13.0/css/all.min.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.7.2/animate.min.css"><script type="application/ld+json">
    {
        "@context": "http://schema.org",
        "@type": "BlogPosting",
        "headline": "《Flutter界面跳转数据交互界面混合开发》",
        "inLanguage": "zh-CN",
        "mainEntityOfPage": {
            "@type": "WebPage",
            "@id": "https:\/\/luckly.work\/flutter%E7%95%8C%E9%9D%A2%E8%B7%B3%E8%BD%AC%E6%95%B0%E6%8D%AE%E4%BA%A4%E4%BA%92%E7%95%8C%E9%9D%A2%E6%B7%B7%E5%90%88%E5%BC%80%E5%8F%91\/"
        },"image": [{
                            "@type": "ImageObject",
                            "url": "https:\/\/luckly.work\/images\/Apple-Devices-Preview.png",
                            "width":  3200 ,
                            "height":  2048 
                        }],"genre": "posts","keywords": "flutter","wordcount":  2154 ,
        "url": "https:\/\/luckly.work\/flutter%E7%95%8C%E9%9D%A2%E8%B7%B3%E8%BD%AC%E6%95%B0%E6%8D%AE%E4%BA%A4%E4%BA%92%E7%95%8C%E9%9D%A2%E6%B7%B7%E5%90%88%E5%BC%80%E5%8F%91\/","datePublished": "2021-07-31T21:50:37+08:00","dateModified": "2021-07-31T21:50:37+08:00","license": "This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.","publisher": {
            "@type": "Organization",
            "name": "xxxx","logo": {
                    "@type": "ImageObject",
                    "url": "https:\/\/luckly.work\/images\/avatar.png",
                    "width":  528 ,
                    "height":  560 
                }},"author": {
                "@type": "Person",
                "name": "早起的年轻人"
            },"description": ""
    }
    </script></head>
    <body header-desktop="fixed" header-mobile="auto"><script type="text/javascript">(window.localStorage && localStorage.getItem('theme') ? localStorage.getItem('theme') === 'dark' : ('auto' === 'auto' ? window.matchMedia('(prefers-color-scheme: dark)').matches : 'auto' === 'dark')) && document.body.setAttribute('theme', 'dark');</script>

        <div id="mask"></div><div class="wrapper"><header class="desktop" id="header-desktop">
    <div class="header-wrapper">
        <div class="header-title">
            <a href="/" title="Lucklyの博客 - 在阅读中遇见自己"><span class="header-title-pre"><i class='far fa-kiss-wink-heart fa-fw'></i></span><span id="id-1" class="typeit"></span></a>
        </div>
        <div class="menu">
            <div class="menu-inner"><a class="menu-item" href="/posts/"> 所有文章 </a><a class="menu-item" href="/categories/flutter/"> Flutter </a><a class="menu-item" href="/categories/read/"> 读书笔记 </a><a class="menu-item" href="/categories/go/"> Go </a><a class="menu-item" href="/tags/"> 标签 </a><a class="menu-item" href="/categories/"> 分类 </a><a class="menu-item" href="/about/"> 关于 </a><a class="menu-item" href="https://github.com/ITmxs" title="GitHub" rel="noopener noreffer" target="_blank"><i class='fab fa-github fa-fw'></i> Github </a><a class="menu-item" href="/friend/"><i class='fas fa-user-friends'></i> 友链 </a><span class="menu-item delimiter"></span><span class="menu-item search" id="search-desktop">
                        <input type="text" placeholder="搜索文章标题或内容..." id="search-input-desktop">
                        <a href="javascript:void(0);" class="search-button search-toggle" id="search-toggle-desktop" title="搜索">
                            <i class="fas fa-search fa-fw"></i>
                        </a>
                        <a href="javascript:void(0);" class="search-button search-clear" id="search-clear-desktop" title="清空">
                            <i class="fas fa-times-circle fa-fw"></i>
                        </a>
                        <span class="search-button search-loading" id="search-loading-desktop">
                            <i class="fas fa-spinner fa-fw fa-spin"></i>
                        </span>
                    </span><a href="javascript:void(0);" class="menu-item theme-switch" title="切换主题">
                    <i class="fas fa-adjust fa-fw"></i>
                </a>
            </div>
        </div>
    </div>
</header><header class="mobile" id="header-mobile">
    <div class="header-container">
        <div class="header-wrapper">
            <div class="header-title">
                <a href="/" title="Lucklyの博客 - 在阅读中遇见自己"><span class="header-title-pre"><i class='far fa-kiss-wink-heart fa-fw'></i></span><span id="id-2" class="typeit"></span></a>
            </div>
            <div class="menu-toggle" id="menu-toggle-mobile">
                <span></span><span></span><span></span>
            </div>
        </div>
        <div class="menu" id="menu-mobile"><div class="search-wrapper">
                    <div class="search mobile" id="search-mobile">
                        <input type="text" placeholder="搜索文章标题或内容..." id="search-input-mobile">
                        <a href="javascript:void(0);" class="search-button search-toggle" id="search-toggle-mobile" title="搜索">
                            <i class="fas fa-search fa-fw"></i>
                        </a>
                        <a href="javascript:void(0);" class="search-button search-clear" id="search-clear-mobile" title="清空">
                            <i class="fas fa-times-circle fa-fw"></i>
                        </a>
                        <span class="search-button search-loading" id="search-loading-mobile">
                            <i class="fas fa-spinner fa-fw fa-spin"></i>
                        </span>
                    </div>
                    <a href="javascript:void(0);" class="search-cancel" id="search-cancel-mobile">
                        取消
                    </a>
                </div><a class="menu-item" href="/posts/" title="">所有文章</a><a class="menu-item" href="/categories/flutter/" title="">Flutter</a><a class="menu-item" href="/categories/read/" title="">读书笔记</a><a class="menu-item" href="/categories/go/" title="">Go</a><a class="menu-item" href="/tags/" title="">标签</a><a class="menu-item" href="/categories/" title="">分类</a><a class="menu-item" href="/about/" title="">关于</a><a class="menu-item" href="https://github.com/ITmxs" title="GitHub" rel="noopener noreffer" target="_blank"><i class='fab fa-github fa-fw'></i>Github</a><a class="menu-item" href="/friend/" title=""><i class='fas fa-user-friends'></i>友链</a><a href="javascript:void(0);" class="menu-item theme-switch" title="切换主题">
                <i class="fas fa-adjust fa-fw"></i>
            </a></div>
    </div>
</header>
<div class="search-dropdown desktop">
    <div id="search-dropdown-desktop"></div>
</div>
<div class="search-dropdown mobile">
    <div id="search-dropdown-mobile"></div>
</div>
<main class="main">
                <div class="container"><div class="toc" id="toc-auto">
            <h2 class="toc-title">目录</h2>
            <div class="toc-content" id="toc-content-auto"></div>
        </div><article class="page single"><h1 class="single-title animated flipInX">《Flutter界面跳转数据交互界面混合开发》</h1><div class="post-meta">
            <div class="post-meta-line"><span class="post-author"><a href="/" title="Author" rel=" author" class="author"><i class="fas fa-user-circle fa-fw"></i>早起的年轻人</a></span>&nbsp;<span class="post-category">收录于 <a href="/categories/flutter/"><i class="far fa-folder fa-fw"></i>Flutter</a></span></div>
            <div class="post-meta-line"><i class="far fa-calendar-alt fa-fw"></i>&nbsp;<time datetime="2021-07-31">2021-07-31</time>&nbsp;<i class="fas fa-pencil-alt fa-fw"></i>&nbsp;约 2154 字&nbsp;
                <i class="far fa-clock fa-fw"></i>&nbsp;预计阅读 5 分钟&nbsp;</div>
        </div><div class="featured-image"><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png"
        data-srcset="https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png, https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png 1.5x, https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png 2x"
        data-sizes="auto"
        alt="https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png"
        title="https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png" /></div><div class="details toc" id="toc-static"  kept="">
                <div class="details-summary toc-title">
                    <span>目录</span>
                    <span><i class="details-icon fas fa-angle-right"></i></span>
                </div>
                <div class="details-content toc-content" id="toc-content-static"><nav id="TableOfContents">
  <ul>
    <li>
      <ul>
        <li><a href="#界面跳转">界面跳转</a>
          <ul>
            <li><a href="#flutter界面内部跳转">Flutter界面内部跳转</a>
              <ul>
                <li><a href="#正常跳转">正常跳转</a></li>
                <li><a href="#带参跳转">带参跳转</a></li>
                <li><a href="#其它跳转方式">其它跳转方式</a></li>
              </ul>
            </li>
            <li><a href="#flutter界面与native界面跳转">Flutter界面与Native界面跳转</a>
              <ul>
                <li><a href="#native界面跳转flutter界面">Native界面跳转Flutter界面</a></li>
                <li><a href="#flutter界面跳转native界面">Flutter界面跳转Native界面</a></li>
              </ul>
            </li>
          </ul>
        </li>
        <li><a href="#数据交互">数据交互</a>
          <ul>
            <li><a href="#flutter调用native">Flutter调用Native</a></li>
            <li><a href="#native调用flutter">Native调用Flutter</a></li>
          </ul>
        </li>
        <li><a href="#界面混合开发">界面混合开发</a>
          <ul>
            <li><a href="#native嵌套flutter">Native嵌套Flutter</a></li>
            <li><a href="#flutter嵌套native">Flutter嵌套Native</a></li>
          </ul>
        </li>
        <li><a href="#heading"></a></li>
      </ul>
    </li>
  </ul>
</nav></div>
            </div><div class="content" id="content"><blockquote>
<p>本文主要介绍</p>
</blockquote>
<h2 id="界面跳转">界面跳转</h2>
<p>Flutter界面跳转设计到两种类型：Flutter界面内部跳转、Flutter与Native界面之间跳转。</p>
<h3 id="flutter界面内部跳转">Flutter界面内部跳转</h3>
<h4 id="正常跳转">正常跳转</h4>
<p>Flutter内部维护一个界面堆栈，跳转时可以直接跳转：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">Navigator.push(context, new MaterialPageRoute(builder: (context) =&gt; new SecondPage()),);
</code></pre></td></tr></table>
</div>
</div><p>也可以预先设置路由，通过路由名称进行跳转</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span><span class="lnt">7
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">routes: {
    &#34;nameRoute&#34;:(BuildContext context)=&gt;new SecondPage(),
    &#34;thirdRoute&#34;:(BuildContext context)=&gt;new ThirdPage(title:&#34;请输入昵称&#34;),
  },
  
  ···
  Navigator.of(context).pushNamed(&#34;nameRoute&#34;);
</code></pre></td></tr></table>
</div>
</div><p>界面返回：</p>
<p>在堆栈中弹出该界面</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">Navigator.pop(context)
</code></pre></td></tr></table>
</div>
</div><h4 id="带参跳转">带参跳转</h4>
<p>带参跳入很简单，只需要在需要跳转的Widget中增加参数就可以了。</p>
<p>带参跳出通过 <code>Navigator.pop(context, [ T result ])</code>中携带具体参数。
接收方需要指定返回结果，例如下面示例：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">Navigator.push&lt;String&gt;(context,
      new MaterialPageRoute(builder: (BuildContext context) {
    return new ThirdPage(title: &#34;请输入昵称&#34;);   /// 跳转到第三页，并且传递参数过去
    })).then((String result) {

    // 接收返回值的逻辑处理，通过一个 Dialog 展示出来
    showDialog(
        context: context,
        builder: (BuildContext context) {
          return new AlertDialog(
            content: new Text(&#34;您输入的昵称为:$result&#34;),
          );
        });
  });
</code></pre></td></tr></table>
</div>
</div><h4 id="其它跳转方式">其它跳转方式</h4>
<ul>
<li>popAndPushNamed 退栈然后入栈一个指定name的页面</li>
<li>popUntil 重复调用pop直到predicate返回true</li>
<li>pushAndRemoveUntil 跳转，然后清栈</li>
</ul>
<h3 id="flutter界面与native界面跳转">Flutter界面与Native界面跳转</h3>
<h4 id="native界面跳转flutter界面">Native界面跳转Flutter界面</h4>
<p>最简单的方式，直接通过Native原生跳转，第二个Native中加载Flutter，不过这种方式不推荐。</p>
<p>实际上同样可以通过router指定具体的page(<strong>这部分存疑，只查到预览版使用该功能，正式版该功能未找到</strong>)，看如下代码：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span><span class="lnt">7
</span><span class="lnt">8
</span><span class="lnt">9
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">View flutterView = Flutter.createView(
  MainActivity.this,
  getLifecycle(),
  &#34;route1&#34;
);
FrameLayout.LayoutParams layout = new FrameLayout.LayoutParams(600, 800);
layout.leftMargin = 100;
layout.topMargin = 200;
setContentView(flutterView);
</code></pre></td></tr></table>
</div>
</div><p>该方法说明见 <a href="https://github.com/flutter/flutter/wiki/Add-Flutter-to-existing-apps#experiment-turn-the-flutter-project-into-a-module" target="_blank" rel="noopener noreffer">Add Flutter to existing apps</a></p>
<p>正式版中未找到相关文档说明，不过在官方代码中有如下示例：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">···

String[] args = getArgsFromIntent(getIntent());
        FlutterMain.ensureInitializationComplete(getApplicationContext(), args);
        
···

FlutterRunArguments runArguments = new FlutterRunArguments();
        runArguments.bundlePath = FlutterMain.findAppBundlePath(getApplicationContext());
        
···

flutterView = getFlutterView();
flutterView.runFromBundle(runArguments);

···

setContentView(flutterView);
</code></pre></td></tr></table>
</div>
</div><p>可以通过参数指定flutter界面的具体信息，并进行展示。</p>
<h4 id="flutter界面跳转native界面">Flutter界面跳转Native界面</h4>
<p>Flutter跳Native界面利用的是<code>MethodChannel</code>，也就是下面数据交互部分的内容。Flutter发送一个信号通知到Native端，执行预设的工作。</p>
<p>例如：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span><span class="lnt">7
</span><span class="lnt">8
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(
  new MethodChannel.MethodCallHandler() {
      @Override
      public void onMethodCall(MethodCall call, MethodChannel.Result result) {
          //打开新的Activity
          startActivity(new Intent(MainActivity.this, FloatingActivity.class));
      }
  });
</code></pre></td></tr></table>
</div>
</div><h2 id="数据交互">数据交互</h2>
<p>Flutter与Native的互相调用，必须通过Platform Channel来实现。</p>
<p>Flutter定义了三种不同的Channel，分别有不同的用途：</p>
<ul>
<li>BasicMessageChannel：用于传递字符串和半结构化的信息</li>
<li>MethodChannel：用于传递方法调用，常用于Flutter调用Native</li>
<li>EventChannel: 用于数据流通信，常用与Native通知Flutter</li>
</ul>
<p>这三种数据交互采用同样的方式，有三个相同的字段：String name、BinaryMessenger messenger、MethodCodec codec.</p>
<p>其中name唯一标识当前channel，messenger进行消息传递，codec用于二进制格式数据与基础数据之间的编解码。</p>
<p>另外还有Handler用于消息处理，存在三种Handler MessageHandler、MethodHandler、StreamHandler分别对应三种Channel</p>
<p>示例如下：</p>
<p>Flutter端</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">static const EventChannel _eventChannel = const EventChannel(&#39;samples.flutter.io/charging&#39;);
static const MethodChannel _methodChannel = const MethodChannel(&#39;samples.flutter.io/battery&#39;);
</code></pre></td></tr></table>
</div>
</div><p>Native端</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">public static void registerWith(Registrar registrar) {
        /**
         * Channel名称：必须与Flutter App的Channel名称一致
         */
        private static final String METHOD_CHANNEL = &#34;samples.flutter.io/battery&#34;;
        private static final String EVENT_CHANNEL = &#34;samples.flutter.io/charging&#34;;

        final MethodChannel methodChannel = new MethodChannel(registrar.messenger(), METHOD_CHANNEL);
        
        final EventChannel eventChannel = new EventChannel(registrar.messenger(), EVENT_CHANNEL);
        eventChannel.setStreamHandler(plugin);
    }
</code></pre></td></tr></table>
</div>
</div><p>首先在Flutter与Native注册Channel的name标识，进行绑定。</p>
<h3 id="flutter调用native">Flutter调用Native</h3>
<p>Flutter端</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">Future&lt;String&gt; getBatteryLevel() async {
    String batteryLevel;
    try {
      final int result = await _methodChannel.invokeMethod(&#39;getBatteryLevel&#39;,{&#39;paramName&#39;:&#39;paramVale&#39;});
      batteryLevel = &#39;Battery level: $result%.&#39;;
    } catch(e) {
      batteryLevel = &#39;Failed to get battery level.&#39;;
    }
    return batteryLevel;
  }
</code></pre></td></tr></table>
</div>
</div><p>Native端</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">methodChannel.setMethodCallHandler(new MethodCallHandler(){

  @Override
    public void onMethodCall(MethodCall call, Result result) {
        if (call.method.equals(&#34;getBatteryLevel&#34;)) {
            Random random = new Random();
            result.success(random.nextInt(100));
        } else {
            result.notImplemented();
        }
    }
});
</code></pre></td></tr></table>
</div>
</div><h3 id="native调用flutter">Native调用Flutter</h3>
<p>Flutter端</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">void listenNativeEvent() {
  _eventChannel.receiveBroadcastStream().listen(_onEvent, onError:_onError);
}

void _onEvent(Object event) {
  print(&#34;Battery status: ${event == &#39;charging&#39; ? &#39;&#39; : &#39;dis&#39;}charging.&#34;);
}

void _onError(Object error) {
  print(&#39;Battery status: unknown.&#39;);
}
</code></pre></td></tr></table>
</div>
</div><p>Native端</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span><span class="lnt">24
</span><span class="lnt">25
</span><span class="lnt">26
</span><span class="lnt">27
</span><span class="lnt">28
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">eventChannel.setStreamHandler(new EventChannel.StreamHandler(){

  @Override
    public void onListen(Object obj, EventChannel.EventSink eventSink) {
        createChargingStateChangeReceiver(eventSink);
    }

    @Override
    public void onCancel(Object obj) {
    }
});

private BroadcastReceiver createChargingStateChangeReceiver(final EventSink events) {
    return new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);

            if (status == BatteryManager.BATTERY_STATUS_UNKNOWN) {
                events.error(&#34;UNAVAILABLE&#34;, &#34;Charging status unavailable&#34;, null);
            } else {
                boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
                        status == BatteryManager.BATTERY_STATUS_FULL;
                events.success(isCharging ? &#34;charging&#34; : &#34;discharging&#34;);
            }
        }
    };
}
</code></pre></td></tr></table>
</div>
</div><h2 id="界面混合开发">界面混合开发</h2>
<p>混合开发同样分为两种:Native嵌套Flutter、Flutter嵌套Native</p>
<h3 id="native嵌套flutter">Native嵌套Flutter</h3>
<p>这部分很简单，直接将FlutterView作为一个简单的View操作就可以了，同样支持xml配置。如：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">protected void onCreate(Bundle savedInstanceState) {
  ···
  super.onCreate(savedInstanceState);
    FlutterMain.ensureInitializationComplete(getApplicationContext(), args);
  setContentView(R.layout.flutter_view_layout);
  ···
  flutterView = findViewById(R.id.flutter_view);
  messageChannel = new BasicMessageChannel&lt;&gt;(flutterView, CHANNEL, StringCodec.INSTANCE);
  ···
}
</code></pre></td></tr></table>
</div>
</div><h3 id="flutter嵌套native">Flutter嵌套Native</h3>
<p>这种方式也不复杂，在Flutter中支持AndroidView、UiKitView来分别支持Android、iOS原生控件展示。以Android为例：</p>
<p>首先在dart语言中设置AndroidView以及该控件的类型标识</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">new Expanded(child: AndroidView(viewType: &#34;ACalendarView&#34;))
</code></pre></td></tr></table>
</div>
</div><p>剩下的就全部在Native端进行配置</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">// 注册类型标识
PluginRegistry.Registrar registrar = registry.registrarFor(key);
        registrar.platformViewRegistry().registerViewFactory(&#34;ACalendarView&#34;, new ACalendarViewFactory(new StandardMessageCodec(), calendarView));
</code></pre></td></tr></table>
</div>
</div><p>指定需要展示的View</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span><span class="lnt">24
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">public class ACalendarViewFactory extends PlatformViewFactory {

    private View calendarView;

    public ACalendarViewFactory(MessageCodec&lt;Object&gt; createArgsCodec, View calendarView) {
        super(createArgsCodec);
        this.calendarView = calendarView;
    }

    @Override
    public PlatformView create(Context context, int i, Object o) {
        return new PlatformView() {
            @Override
            public View getView() {
                return calendarView;
            }

            @Override
            public void dispose() {

            }
        };
    }
}
</code></pre></td></tr></table>
</div>
</div><h2 id="heading"></h2></div><div class="post-footer" id="post-footer">
    <div class="post-info">
        <div class="post-info-line">
            <div class="post-info-mod">
                <span>更新于 2021-07-31</span>
            </div>
            <div class="post-info-license"></div>
        </div>
        <div class="post-info-line">
            <div class="post-info-md"></div>
            <div class="post-info-share">
                <span><a href="javascript:void(0);" title="分享到 Twitter" data-sharer="twitter" data-url="https://luckly.work/flutter%E7%95%8C%E9%9D%A2%E8%B7%B3%E8%BD%AC%E6%95%B0%E6%8D%AE%E4%BA%A4%E4%BA%92%E7%95%8C%E9%9D%A2%E6%B7%B7%E5%90%88%E5%BC%80%E5%8F%91/" data-title="《Flutter界面跳转数据交互界面混合开发》" data-hashtags="flutter"><i class="fab fa-twitter fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Facebook" data-sharer="facebook" data-url="https://luckly.work/flutter%E7%95%8C%E9%9D%A2%E8%B7%B3%E8%BD%AC%E6%95%B0%E6%8D%AE%E4%BA%A4%E4%BA%92%E7%95%8C%E9%9D%A2%E6%B7%B7%E5%90%88%E5%BC%80%E5%8F%91/" data-hashtag="flutter"><i class="fab fa-facebook-square fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Hacker News" data-sharer="hackernews" data-url="https://luckly.work/flutter%E7%95%8C%E9%9D%A2%E8%B7%B3%E8%BD%AC%E6%95%B0%E6%8D%AE%E4%BA%A4%E4%BA%92%E7%95%8C%E9%9D%A2%E6%B7%B7%E5%90%88%E5%BC%80%E5%8F%91/" data-title="《Flutter界面跳转数据交互界面混合开发》"><i class="fab fa-hacker-news fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Line" data-sharer="line" data-url="https://luckly.work/flutter%E7%95%8C%E9%9D%A2%E8%B7%B3%E8%BD%AC%E6%95%B0%E6%8D%AE%E4%BA%A4%E4%BA%92%E7%95%8C%E9%9D%A2%E6%B7%B7%E5%90%88%E5%BC%80%E5%8F%91/" data-title="《Flutter界面跳转数据交互界面混合开发》"><i data-svg-src="https://cdn.jsdelivr.net/npm/simple-icons@2.14.0/icons/line.svg"></i></a><a href="javascript:void(0);" title="分享到 微博" data-sharer="weibo" data-url="https://luckly.work/flutter%E7%95%8C%E9%9D%A2%E8%B7%B3%E8%BD%AC%E6%95%B0%E6%8D%AE%E4%BA%A4%E4%BA%92%E7%95%8C%E9%9D%A2%E6%B7%B7%E5%90%88%E5%BC%80%E5%8F%91/" data-title="《Flutter界面跳转数据交互界面混合开发》" data-image="https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png"><i class="fab fa-weibo fa-fw"></i></a></span>
            </div>
        </div>
    </div>

    <div class="post-info-more">
        <section class="post-tags"><i class="fas fa-tags fa-fw"></i>&nbsp;<a href="/tags/flutter/">flutter</a></section>
        <section>
            <span><a href="javascript:void(0);" onclick="window.history.back();">返回</a></span>&nbsp;|&nbsp;<span><a href="/">主页</a></span>
        </section>
    </div>

    <div class="post-nav"><a href="/flutter%E6%B8%B2%E6%9F%93%E5%8E%9F%E7%90%86%E4%B8%8E%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96/" class="prev" rel="prev" title="《Flutter渲染原理与性能优化》"><i class="fas fa-angle-left fa-fw"></i>《Flutter渲染原理与性能优化》</a>
            <a href="/flutter%E5%AD%A6%E4%B9%A0%E8%B5%84%E6%96%99%E6%95%B4%E7%90%863/" class="next" rel="next" title="《Flutter学习资料整理3》">《Flutter学习资料整理3》<i class="fas fa-angle-right fa-fw"></i></a></div>
</div>
</article></div>
            </main><footer class="footer">
        <div class="footer-container"><div class="footer-line">由 <a href="https://gohugo.io/" target="_blank" rel="noopener noreffer" title="Hugo 0.79.1">Hugo</a> 强力驱动 | 主题 - <a href="https://github.com/dillonzq/LoveIt" target="_blank" rel="noopener noreffer" title="LoveIt 0.2.10"><i class="far fa-kiss-wink-heart fa-fw"></i> LoveIt</a>
                </div><div class="footer-line"><i class="far fa-copyright fa-fw"></i><span itemprop="copyrightYear">2021</span><span class="author" itemprop="copyrightHolder">&nbsp;<a href="/" target="_blank">早起的年轻人</a></span>&nbsp;|&nbsp;<span class="license"><a rel="license external nofollow noopener noreffer" href="https://creativecommons.org/licenses/by-nc/4.0/" target="_blank">CC BY-NC 4.0</a></span></div>
        </div>
    </footer></div>

        <div id="fixed-buttons"><a href="#" id="back-to-top" class="fixed-button" title="回到顶部">
                <i class="fas fa-arrow-up fa-fw"></i>
            </a><a href="#" id="view-comments" class="fixed-button" title="查看评论">
                <i class="fas fa-comment fa-fw"></i>
            </a>
        </div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/cookieconsent@3.1.1/build/cookieconsent.min.css"><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/smooth-scroll@16.1.3/dist/smooth-scroll.min.js"></script><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/autocomplete.js@0.37.1/dist/autocomplete.min.js"></script><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/algoliasearch@4.2.0/dist/algoliasearch-lite.umd.min.js"></script><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/lazysizes@5.2.2/lazysizes.min.js"></script><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/clipboard@2.0.6/dist/clipboard.min.js"></script><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/sharer.js@0.4.0/sharer.min.js"></script><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/typeit@7.0.4/dist/typeit.min.js"></script><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/cookieconsent@3.1.1/build/cookieconsent.min.js"></script><script type="text/javascript">window.config={"code":{"copyTitle":"复制到剪贴板","maxShownLines":10},"comment":{},"cookieconsent":{"content":{"dismiss":"同意","link":"了解更多","message":"本网站使用 Cookies 来改善您的浏览体验."},"enable":true,"palette":{"button":{"background":"#f0f0f0"},"popup":{"background":"#1aa3ff"}},"theme":"edgeless"},"data":{"id-1":"早起的年轻人","id-2":"早起的年轻人"},"search":{"algoliaAppID":"PASDMWALPK","algoliaIndex":"index.zh-cn","algoliaSearchKey":"b42948e51daaa93df92381c8e2ac0f93","highlightTag":"em","maxResultLength":10,"noResultsFound":"没有找到结果","snippetLength":50,"type":"algolia"},"typeit":{"cursorChar":"|","cursorSpeed":1000,"data":{"id-1":["id-1"],"id-2":["id-2"]},"duration":-1,"speed":100}};</script><script type="text/javascript" src="/js/theme.min.js"></script></body>
</html>
